//#pragma comment(linker, "/subsystem:windows /entry:mainCRTStartup")

#include "OCMain/HttpClient.h"
#include "OCMain/Environment.h"
#include "OCMain/DynLibManager.h"
#include "OCMain/ArgumentParser.h"
#include "OCMain/Timer.h"
#include "OCGrib/GribVolume.h"
#include "OCNetCDF/NetCDFReader.h"
#include "OCVolume/VolumeUtil.h"

using namespace OCPP;
using namespace OCPP::Volume;
Environment* mEnvironment = NULL;

#if WIN32
#include <Windows.h>
BOOL WINAPI HandlerRoutine(DWORD dwCtrlType) {

    if (CTRL_CLOSE_EVENT == dwCtrlType) {
        CORE_SAFE_DELETE(mEnvironment);
    }

    return TRUE;
}
typedef void (*DLL_START_PLUGIN)(void);
typedef void (*DLL_STOP_PLUGIN)(void);
void initEnv() {
    SetConsoleCtrlHandler(HandlerRoutine, true);
}
#else
void initEnv() {}
#endif

void setEnv(String application)
{
    String name, ext, path;
    StringUtil::splitFullFilename(application, name, ext, path);
    path = StringUtil::replaceAll(path, "\\", "/");
    mEnvironment = new Environment(path);
    mEnvironment->loadConfig(path + "config.ini");
}

int main(int argc, char** argv)
{
    ArgumentParser arguments(&argc, argv);

    arguments.getApplicationUsage()->setCommandLineUsage("OCVolumeConverter");
    arguments.getApplicationUsage()->addCommandLineOption("-i", "file to read");
    arguments.getApplicationUsage()->addCommandLineOption("-o", "path write to");
    arguments.getApplicationUsage()->addCommandLineOption("-var", "var name in nc");


    initEnv();
    setEnv(arguments.getApplicationName());
    String fileName;
    String outPath;

    arguments.read("-i", fileName);
    arguments.read("-o", outPath);

    if (arguments.read("-h") || arguments.read("--help") 
        || fileName.empty() || outPath.empty())
    {
        arguments.getApplicationUsage()->write(std::cout);
        return 1;
    }

    String name, ext, path;
    StringUtil::splitFullFilename(fileName, name, ext, path);
    StringUtil::toLowerCase(ext);
    if (ext == "nc") {
        String var;
        arguments.read("-var", var);
        AutoTimer timer;
        NetCDFReader reader;
        reader.open(fileName);
        VolumeOptions options(new VolumeD3Writer());
        options.getWriter().setOutputPath(outPath);
        reader.extract(var, options);
    }else {
        GribVolume reader;
        reader.extract(fileName, outPath);
    }

	return 0;
}
